import Taro, { Component } from '@tarojs/taro'
import { Swiper, SwiperItem, Image, View, Text,Button,RichText } from '@tarojs/components'
import '../../assets/common.scss'
import CommonJs from '../../utils/common'
import '../../assets/animate.min.scss'
import './mall.scss'

import goto from './images/goto01.png'
import kefu from './images/myorder10.png'
import gwc from './images/myorder11.png'
import close from './images/close.png'
import timg from './images/timg.png'
 
export default class Index extends Component {
  constructor(props) {
    super(props);
    this.state = {
		result:[],
		userinfo:'',  
		mysj:'',
	     width:320, 
		   introduction:"",
		   showgg:0,
		   ggindex:0,
		   goodsnum:1,
	     yhqlist:[],
	     gwinfo:"",
	     qid:'',
	     ish5:0,
	     ewm:'',
	     goodsinfo:{
	      "itemSkuList":[{"name":"","saleStock":{"saleAmount":0,"stockAmount":200},"price":{"marketPrice":'',"specialPrice":''}}],
	     	"itemPictureList":[],
	     	"itemDescription":{"samllDescription":""},
	     	"saleStock":{"saleAmount":0,"stockAmount":200},
	     	"price":{"marketPrice":7200,"specialPrice":3900}
	    },
	    shareCode:'',
	    istgshow:0,
		malltype:'',
		appmark:CommonJs.getmark()
		}
  }
  config = {
    navigationBarTitleText: '加载中'
  }

  open(url,type,malltype){
  	if (Taro.getEnv() === Taro.ENV_TYPE.WEAPP) {
	    this.$preload({
		  type:type,
		  malltype:malltype
	    })
    } 
    else if (Taro.getEnv() === Taro.ENV_TYPE.WEB) {
    	if(type){
      	url = url+'?type='+type
     }
    	
    }
    
    CommonJs.openTo(url);
  }


  componentWillMount () {
    this.getQunName();
    this.getscreeninfo();
    if (Taro.getEnv() === Taro.ENV_TYPE.WEAPP) {
    	var malltype=this.$router.preload.malltype
    	if(malltype){
	    	this.setState({
	        malltype:malltype
	      })
	    }
    	var goodsid=this.$router.preload.type;
    	var gid=goodsid;
      this.goodsxq(gid,malltype);
      this.getsharecode()
      this.getsharemonery(gid)
    } 
    else{
      this.goodsxq(this.$router.params.type);
      this.settype()
    }
	var dateinfo = Taro.getStorageSync('dateinfo')
    var userinfo=Taro.getStorageSync('userinfo');
    userinfo.userid=dateinfo.userid;
    this.setState({
      userinfo:userinfo
    })
    
    this.getgw();
    this.getmysj();
    this.gettglist();
    
	}


  componentDidMount () {}

  componentWillUnmount () { }

  componentDidShow () { 
  	CommonJs.getFootPrint('GO',4,this.$router.params.type);
  }

  componentDidHide () { }
  onShareAppMessage(){
	  var goodsinfo=this.state.goodsinfo;
    let title = '"【特惠推荐】'+goodsinfo.name+'"，特价'+goodsinfo.price.specialPrice/100+'元，数量有限，先到先得'
    var dateinfo = Taro.getStorageSync('dateinfo');
    var shopId=Taro.getStorageSync('shopId');
    var goodsId=goodsinfo.id;
    var url='/pages/mall/index?scene='
    if(this.state.malltype=='UC'){
			url='/pages/mall/ucindex?scene='
			var path = url+dateinfo.qid+'goodsxq'+shopId+'goodsxq'+goodsId
		}
		else if(this.state.malltype=='WUC'){
			url='/pages/mall/wucindex?scene='
			var path = url+dateinfo.qid+'goodsxq'+shopId+'goodsxq'+goodsId
		}
		else{
	    var shareCode=this.state.shareCode;
	    if(!shareCode){
	    	var path = url+dateinfo.qid+'goodsxq'+shopId+'goodsxq'+goodsId
	    }
	    else{
	    	var path = url+dateinfo.qid+'goodstg'+goodsId+'goodstg'+shareCode
	    }
	 }
    var imageUrl = goodsinfo.logoUrl
    console.log(path+"///sqqqqqqqq")
    return CommonJs.onShareAppMessage(title, path, imageUrl)
    
  }

  getscreeninfo(){
    var _this=this;
    Taro.getSystemInfo({
      success:function(res){
      var windowWidth = res.windowWidth;
      _this.setState({
        width:windowWidth
      })
      }
    })
  }
  settype(){
  	this.setState({
	    ish5:1
	  })
  }
  chat(){
  	var gwinfo=this.state.gwinfo;
  	this.$preload({
      'friendId':gwinfo.consultant.id,
      'name':gwinfo.consultant.accountName,
      'byfrom':'guwen'
    });
  	CommonJs.openTo("/pages/chat/chat");
  }
  getgw(){
  	var _this=this;
    var dateinfo = Taro.getStorageSync('dateinfo')
    var cid=dateinfo.qid;
  	if(cid){
    	var url="/crmweb/papi/v1.9/customer-shop/findByShopIdAndUserId/"+cid
    	CommonJs.ajaxRequest(url,'','GET',function(res){
    		if(res.data){
  				_this.setState({
  		     	gwinfo:res.data
  		    })
  			}
    	},"wfw")
    }
  }
  bdgw(){
  	var _this=this;
  	var url="/crmweb/papi/v1.9/customer-shop/crate/customerShop?consultantId="+this.state.gwinfo.consultant.id
  	CommonJs.ajaxRequest(url,'','POST',function(res){
  		console.log(JSON.stringify(res))
  		Taro.showToast({
        title:'加载中..',
        icon: 'none',
        duration: 2000
      });
      setTimeout(function(){
      	_this.chat();
      },2000)

  	},"wfw")
  }
  getyhq(shopid){
    //var shopid=Taro.getStorageSync('shopId');
  	var url="/crm/papi/v1.9/coupon/publish?shopId.equals="+shopid;
  	var _this=this
  	CommonJs.ajaxRequest(url,'','GET',function(res){
       _this.setState({
         yhqlist: res.data.list
       })
       
  	},"wfw")
  }
  getQunName(){
	var dateinfo = Taro.getStorageSync('dateinfo')
    var date1={id:dateinfo.qid}
    CommonJs.ajaxRequest('/cluster/getEntityAndLoginId',date1,'GET',function(res){
      if(res.content){
		
	  }
    })
  }
  goodsxq(goodsid,malltype){
		if(goodsid){
			CommonJs.getFootPrint('COME',4,goodsid,malltype);
			if(malltype=='UC'){
				var url='/mallbean/papi/v1.9/item/'+goodsid
			}
			else if(malltype=='WUC'){
				var url='/mallcredit/papi/v1.9/item/'+goodsid
			}
			else{
				var url='/mall/papi/v1.9/item/'+goodsid
			}
			var _this=this;
			CommonJs.ajaxRequest(url,'','GET',function(res){
			   _this.setState({
					goodsinfo: res.data
			  })
			  Taro.setNavigationBarTitle({title:res.data.name})
			  Taro.setStorage({key:'shopId',data:res.data.shop.shopId})
				_this.getqid(res.data.shop.shopId)
				_this.getyhq(res.data.shop.shopId);
			},'wfw')
		}
  }
  getqid(shopid){
  	var url='/clusterShop/getClusterShopByShopId?shopId='+shopid
  	var _this=this;
		CommonJs.ajaxRequest(url,'','GET',function(res){
		   _this.setState({
				qid: res.content.clusterId
		  })
		})
  	
  }
  showggfun(val){
	  if(val==1){
		this.setState({
		  showgg:1
		})
	  }
	  else{
		this.setState({
		  showgg:0
		})
	  }
  }
  addcar(){
    var shopId = this.state.goodsinfo.shop.shopId;
    var goodsinfo=this.state.goodsinfo;
	var index=this.state.ggindex;
    var _this=this;
	var malltype = _this.state.malltype
	 if(malltype == 'UC'){
		var url='/mallbean/papi/v1.9/carts/cartItem';
	 }
	 else if(malltype == 'WUC'){
		var url='/mallcredit/papi/v1.9/carts/cartItem';
	 }
	 else{
		var url='/mall/papi/v1.9/carts/cartItem';
	 }
    var dates={
      "product": {
        "amount":this.state.goodsnum,
        "itemId":goodsinfo.id,
        "itemSkuId":goodsinfo.itemSkuList[index].id,
        "shopId":shopId,
        "shopName": "",
        "limitAmount": 0
      }
    }
    CommonJs.ajaxRequest(url,dates,'POST',function(res){
      Taro.showModal({
        title: '添加成功',
        content: '是否查看购物车',
        success:function(ret){
          if(ret.confirm){
            _this.open('/pages/mall/shopcar','',malltype)
          }
        }
      })
    },'wfw')
  }
  choosegg(index){
  
		this.setState({
		  ggindex:index
		})
  }
  reducegoods(){
	var num=this.state.goodsnum;
	if(num>1){
	  num=num-1
	  this.setState({
		goodsnum:num
	  })
	}
	else{
		Taro.showToast({
		  title:'购买数量不能少于1哟',
		  icon: 'none',
		  duration: 2000
		})
	}
  }
  addgoods(){
	  var num=this.state.goodsnum;
	  var index=this.state.ggindex;
	  var goodsinfo=this.state.goodsinfo;
	  if(num<goodsinfo.itemSkuList[index].saleStock.stockAmount){
		  num=num+1
		  this.setState({
			goodsnum:num
		  })
	  }
	  else{
		Taro.showToast({
		  title:'库存不够啦',
		  icon: 'none',
		  duration: 2000
		})
	  }
  }
  buynow(){
  		var goodsinfo=this.state.goodsinfo;
			var index=this.state.ggindex;
			var query=[];
			var obj={};
			obj.name=goodsinfo.name;
			obj.logoUrl=goodsinfo.logoUrl;
			obj.amount=this.state.goodsnum;
			obj.itemId=goodsinfo.id;
			obj.itemSkuId=goodsinfo.itemSkuList[index].id;
			obj.price=goodsinfo.itemSkuList[index].price.specialPrice;
			obj.ggname=goodsinfo.itemSkuList[index].name;
			obj.weight=goodsinfo.itemSkuList[index].weight;
			obj.malltype=this.state.malltype;
			obj.agentShopId=Taro.getStorageSync('shopId')
			query.push(obj)
			this.open('/pages/mall/order',query)
		
  }
  geth5ewm(){
  	var _this=this;
		var goodsinfo=this.state.goodsinfo;
		var shopid=goodsinfo.shop.shopId;
		var goodsid=goodsinfo.id
		var qid=this.state.qid
		var url='/clusterlog/getWxSmallQrCode?page=pages/mall/index&scene='+qid+'goodsxq'+goodsid
		CommonJs.ajaxRequest(url,'','POST',function(res){
			if(res.code==200){
	     	_this.setState({
					ewm: res.content
			  })
	    }
			else{
				Taro.showToast({
				  title:res.content,
				  icon: 'none',
				  duration: 2000
				})
			}
    })
  }
  closeewm(){
  	this.setState({
				ewm:''
		})
  }
  getsharecode(){
  	/*获取推广大使的推广码*/
  	var url='/retail/papi/v1.9/share-code'
  	var _this=this;
  	CommonJs.ajaxRequest(url,'','POST',function(res){
  		console.log(JSON.stringify(res.data+"//推广码"))
  		if(res.data){
				_this.setState({
					shareCode: res.data.shareCode
			  })
  		}
  	},'wfw')
  }
  getsharemonery(goodsid){
  	/*获取推广大使的推广佣金*/
  	var shopid=Taro.getStorageSync('shopId');
  	var url='/retail/papi/v1.9/share-bonus/item/'+shopid+'/'+goodsid
  	var _this=this;
  	CommonJs.ajaxRequest(url,'','GET',function(res){
  		console.log(JSON.stringify(res.data)+"//推广佣金")
  		if(res.data){
				_this.setState({
					sharemonery:res.data.firstBonus
			  })
				var dateinfo = Taro.getStorageSync('dateinfo');
				if(res.data.firstBonus>0&&!dateinfo.userid&&!_this.state.malltype){
					
					_this.setState({
						istgshow:1
				  })
				}
  		}
  	},'wfw')
  }
  istgtips(){
  	var _this=this;
  	Taro.showModal({
		  title: '您还未登录，请先登录',
		  content: '推广商推广本商品可活动佣金哟',
		  success: function (res) {
		    if (res.confirm) {
		      CommonJs.openTo('/pages/login/login')
		    } 
		    else if (res.cancel) { 
		    	Taro.showToast({
	          title:'登录后分享可以活动佣金哟',
	          icon: 'none',
	          duration: 2000
	        })
		    }
		  }
		})
  }

  gotoshop(sid,did){
  	Taro.setStorage({key:'shopId',data:sid})
		Taro.setStorage({key:'dealerId',data:did})
		var url='/clusterShop/getClusterShopByShopId?shopId='+sid
  	var _this=this;
		CommonJs.ajaxRequest(url,'','GET',function(res){
			var dateinfo = Taro.getStorageSync('dateinfo')
			if(!dateinfo){
				dateinfo={}
			}
			var qid=''
			if(res.content){
				if(res.content.clusterId){
					qid=res.content.clusterId
				}
			}
			dateinfo.qid=qid
			Taro.setStorage({key:'dateinfo',data:dateinfo})
		  CommonJs.openTo('/pages/mall/shopindex')
		}) 
  	
  }
  getmysj(){
  	
	var url='/retail/papi/v1.9/sharer/getusers/introducer'
	var _this=this
	CommonJs.ajaxRequest(url,'','GET',function(res){
		var ret=res.data;
		var arr=[{},{}];
		if(ret&&ret.gradeChainList&&ret.gradeChainList.length>0){
			var red=ret.gradeChainList;
			for(var i=0;i<red.length;i++){
				if(red[i].gradeSettingId==2){
					arr[0]=red[i]
				}
				if(red[i].gradeSettingId==3){
					arr[1]=red[i]
				}
			}
			
		}
		else{
			ret={}
		}
		ret.sjlist=arr;
	  _this.setState({
		mysj:ret
	  })
	},"wfw")
}
gettglist(pageNumber){
	var url='/retail/papi/v1.9/sharer/query/subordinates'
	var _this=this
	var dates={
		shopId:Taro.getStorageSync('shopId'),
  }

  CommonJs.ajaxRequest(url,dates,'GET',function(res){		
		  var result = res.data.list
		  var results = _this.state.result
	  for(var i = 0; i < result.length; i++){
		results.push(result[i]);
	  }
		_this.setState({
		  result: results,

		})
  },"wfw")
}
  render () {
    const goodsinfo=this.state.goodsinfo;
	const ggindex=this.state.ggindex;
	const goodsnum=this.state.goodsnum;
  const yhqlist =this.state.yhqlist;
  const mysj =this.state.mysj;
  const userinfo=this.state.userinfo
  const result = this.state.result
  const appmark=this.state.appmark
    return (
      <View className='page'>
        <View className='mallPage'>
			<View className='focusImg focusImg01' style={'height:'+this.state.width+'PX'}>
				<Swiper
				className="swiper-container" style="height:100%;"
				circular
				indicatorDots
				indicatorColor='#999'
				indicatorActiveColor='#bf708f'
				autoplay>
			
				<SwiperItem>
					<Image className="swiper-img" mode="widthFix" src={goodsinfo.logoUrl}></Image>
				 </SwiperItem>
				 

			  </Swiper>
			</View>
			<View className='goodsinfo'>
				
				<Button openType='share' className='goods-share' style={this.state.istgshow!=0?'display:none':''}>
					<Image className='qun-fnxnimg' mode='scaleToFill' src='https://minichat.g2ma.com/kedouimg/40.png'></Image>
				</Button>
				<View className='goods-share' style={this.state.istgshow==0?'display:none':'padding:10px 3%;'} onClick={this.istgtips.bind(this)}>
					<Image className='qun-fnxnimg' mode='scaleToFill' src='https://minichat.g2ma.com/kedouimg/40.png'></Image>
				</View>
				<View className='goods-pri'>
					<Text className='qian' style={this.state.malltype?'display:none':''}>￥</Text>
					<Text className='qian' style={this.state.malltype=='UC'?'':'display:none'}>UC</Text>
					<Text className='qian' style={this.state.malltype=='WUC'?'':'display:none'}>WUC</Text>
					<Text className='pri'>{goodsinfo.itemSkuList.length>0?goodsinfo.itemSkuList[ggindex].price.specialPrice/100:goodsinfo.price.specialPrice/100}</Text>
					<Text className='sharemonery' style={this.state.sharemonery&&!this.state.malltype?'':'display:none'}>推广可获得{this.state.sharemonery}%的佣金</Text>
				</View>
				<View className='goods-tit'>{goodsinfo.name}</View>
				<View className='goods-other'>
					<Text className='goods-yj' style={this.state.malltype?'display:none':''}>原价：￥{goodsinfo.price.marketPrice?goodsinfo.price.marketPrice/100:goodsinfo.price.specialPrice/100*1.5}</Text>
					<Text className='goods-yj' style={this.state.malltype=='UC'?'':'display:none'}>原价：UC{goodsinfo.price.marketPrice?goodsinfo.price.marketPrice/100:goodsinfo.price.specialPrice/100*1.5}</Text>
					<Text className='goods-yj' style={this.state.malltype=='WUC'?'':'display:none'}>原价：WUC{goodsinfo.price.marketPrice?goodsinfo.price.marketPrice/100:goodsinfo.price.specialPrice/100*1.5}</Text>
					<Text className='goods-kc'>库存：{goodsinfo.saleStock.stockAmount}件</Text>
					<Text className='goods-xl'>销量：{goodsinfo.saleStock.saleAmount}件</Text>
				</View>
				<View className='goods-shop' onClick={this.gotoshop.bind(this,goodsinfo.shop.shopId,goodsinfo.shop.dealerId)}>
					<View className='goods-tit' style="padding:0 0 20rpx 0">所属门店</View>
					<Image className="shop-img" mode="scaleToFill" src={goodsinfo.shop.rotationPictures?goodsinfo.shop.rotationPictures:timg}></Image>
					<Text className='shop-name'>{goodsinfo.shop.shopName}</Text>
				</View>
				
				<View className='goods-shop' style={appmark=='xjzb'?'':'display:none'}>
				<View className='goods-tit' style="padding:0 0 20rpx 0">朔源</View>
				<ScrollView scrollX style='white-space:nowrap;'>
					<View className='gxl-li'>
					<Image className="shop-img" mode="scaleToFill" src={mysj.imageUrl?mysj.imageUrl:CommonJs.getlogo()}></Image>
					<Text className='shop-name' style='display:block'>{mysj.mobile?mysj.mobile:'暂无'}</Text>
					</View>
					<View className='gxl-li'>
					<Image className="shop-img" mode="scaleToFill" src={userinfo.avatarUrl?userinfo.avatarUrl:CommonJs.getlogo()}></Image>
					<Text className='shop-name' style='display:block'>{userinfo.mobile?userinfo.mobile:'暂无'}</Text>
					</View>
					{result.map((item, index) => (
    			<View className='gxl-li'>
				<Image className="shop-img" mode="scaleToFill" src={item.avatar?item.avatar:CommonJs.getlogo()}></Image>
				<Text className='shop-name' style='display:block'>{item.mobile}</Text>
				</View>
    			))}
         		 </ScrollView>
					
				</View>

				<View className='goods-yhq' style={yhqlist.length>0?'display:block;':'display:none'} onClick={this.open.bind(this,'/pages/mall/yhq','')}>
					优惠券：<Text className='goods-yhqvalue' style='overflow:inherit'>{yhqlist[0]?yhqlist[0].name:''}</Text>
					<Image className="goto" mode="widthFix" src={goto}></Image>
				</View>
				<View className='goods-yhq goods-gg' onClick={this.showggfun.bind(this,1)}>
					已选择：<Text className='goods-yhqvalue'>{goodsinfo.itemSkuList[ggindex].name}</Text>
					<Image className="goto" mode="widthFix" src={goto}></Image>
				</View>
				<View className='goods-xq'>
					<View className='goods-xq-tit'>产品详情</View>
					<View className='goods-xq-con'>
						<RichText  className='qun-hodotxt txt1' nodes={goodsinfo.itemDescription.samllDescription} />
					</View>
				</View>

				




				<View className='goods-btn' style={this.state.ish5==0?'display:block':'display:none'}>
					<View className='goods-btn-list'>
						<Text className='shopcar' onClick={this.addcar.bind(this)}>加入购物车</Text>
						<Text className='buy' onClick={this.buynow.bind(this)} >立即购买</Text>
					</View>
					<View className='goods-kf' onClick={this.bdgw.bind(this)} style={this.state.gwinfo?'':'display:none'}>
						<Image className="kf" mode="widthFix" src={kefu}></Image>
					</View>
					<View className='goods-kf' onClick={this.open.bind(this,'/pages/mall/shopcar','',this.state.malltype)}>
						<Image className="kf" mode="widthFix" src={gwc}></Image>
						<Text className='kftext' style='display:none;'>1</Text>
					</View>
				</View>
				{/* <View className='goods-btn' style={this.state.ish5==0&&this.state.malltype?'display:block':'display:none'}>
					<View className='goods-btn-list' style="width:100%">
						<Text className='buy' onClick={this.buynow.bind(this)} style='border-radius:60px;width:94%;margin:0 auto;display:block;'>立即购买</Text>
					</View>
				</View> */}
				<View className='goods-btn' style={this.state.ish5==1?'display:block':'display:none'}>
				 
					<View className='goods-btn-list' style="width:100%">
					   更多优惠在小程序等着你
						<Text className='buy' onClick={this.geth5ewm.bind(this)} style='border-radius:60px;float:right;'>立即购买</Text>
					</View>
				</View>
				
				<View className='showewm' style={this.state.ewm?'display:block':'display:none'}>
						<View className='showewm-box'>
							<View className='showewm-tit'>长按识别二维码购买</View>
							<View className='showewm-con'>
									<Image className="kf" mode="widthFix" src={this.state.ewm}></Image>
							</View>
							<View className='showewm-btn' onClick={this.closeewm.bind(this)}>关闭</View>
						</View>
				</View>
				
				<View className={this.state.showgg==1?'choose-gg animated bounceInUp':'choose-gg hiddgg'}>
					 <View className='goods-li'>
						<View className='cat-li-img'>
							<Image className="cat-img" mode='scaleToFill' src={goodsinfo.logoUrl?goodsinfo.logoUrl:'https://minichat.g2ma.com/kedouimg/A6984900727459logo.png'}></Image>
						</View>
						<View className='sp-info'>
							<Text className='sp-name'>{goodsinfo.name}</Text>
							<Text className='sp-price'>￥{goodsinfo.itemSkuList[ggindex].price.specialPrice/100}</Text>
							<Text className='sp-kc'>库存：{goodsinfo.itemSkuList[ggindex].saleStock.stockAmount}件</Text>
						</View>
					</View>
					<View className='choose-gg01'>
						<View className='choose-gg-tit'>选择商品规格</View>
						<View className='choose-gg-list'>

							{goodsinfo.itemSkuList.map((item, index) => (
							<Text className={index==ggindex?'gg ggcur':'gg'} onClick={this.choosegg.bind(this,index)}>{item.name}</Text>
							))}
						</View>
					</View>

					<View className='choose-gg01 choose-sl'>
						<View className='choose-gg-tit'>数量</View>
						<View className='choose-gg-list'>
							<Text className='jian' onClick={this.reducegoods}>-</Text>
							<Text className='input'>{goodsnum}</Text>
							<Text className='jia' onClick={this.addgoods}>+</Text>
						</View>
					</View>
					<Image className="choose-close" mode="widthFix" src={close}  onClick={this.showggfun.bind(this,0)}></Image>
				</View>
			</View>
		</View>
      </View>
    )
  }
}
